package com.cloud.thelen.wallpaper;

import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.cloud.thelen.wallpaper.Adapter.WallpaperAdapter;
import com.cloud.thelen.wallpaper.Dao.Dao;
import com.cloud.thelen.wallpaper.Model.DaoUtils;
import com.cloud.thelen.wallpaper.databinding.ActivityWallpaperBinding;
import com.google.android.material.snackbar.Snackbar;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class WallpaperActivity extends AppCompatActivity {

    private ActivityWallpaperBinding activityWallpaperBinding;

    private WallpaperAdapter adapter;

    private List<String> links;

    private DaoUtils daoUtils;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityWallpaperBinding = ActivityWallpaperBinding.inflate(getLayoutInflater());
        setContentView(activityWallpaperBinding.getRoot());
        activityWallpaperBinding.recycler.setOffscreenPageLimit(3);
        daoUtils = new DaoUtils(this);
        links = getIntent().getStringArrayListExtra("links");
        int position = getIntent().getIntExtra("number", 0);
        adapter = new WallpaperAdapter(this, 3);
        adapter.setView(activityWallpaperBinding.dialog);
        adapter.setData(links);
        activityWallpaperBinding.recycler.setAdapter(adapter);
        activityWallpaperBinding.recycler.setCurrentItem(position, false);
        activityWallpaperBinding.Cancel.setOnClickListener(l -> {
            activityWallpaperBinding.dialog.setVisibility(View.GONE);
        });
        activityWallpaperBinding.dialog.setOnClickListener(l->{
            onBackPressed();
        });
        activityWallpaperBinding.back.setOnClickListener(l -> {
            onBackPressed();
        });
        activityWallpaperBinding.title.setOnClickListener(l -> {
            onBackPressed();
        });
        activityWallpaperBinding.download.setOnClickListener(l -> {
            Glide.with(getApplicationContext())
                    .downloadOnly()
                    .load(links.get(activityWallpaperBinding.recycler.getCurrentItem()))
                    .listener(new RequestListener<File>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Snackbar.make(activityWallpaperBinding.recycler, "Download Fail", Snackbar.LENGTH_SHORT).show();
                                    activityWallpaperBinding.dialog.setVisibility(View.GONE);
                                }
                            });
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
                            try {
                                InputStream inputStream = new FileInputStream(resource);
                                byte[] bytes = new byte[1024];
                                String sdCardPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
                                String names = System.currentTimeMillis() + ".png";
                                File file = new File(sdCardPath, names);
                                FileOutputStream fos = new FileOutputStream(file);
                                int len = -1;
                                while ((len = inputStream.read(bytes)) != -1) {
                                    fos.write(bytes, 0, len);
                                }
                                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        String path = file.getPath();
                                        Dao dao = new Dao();
                                        dao.setImg(path);
                                        daoUtils.insert(dao);
                                        Snackbar snackbar = Snackbar.make(activityWallpaperBinding.recycler, "Download Success", Snackbar.LENGTH_SHORT);
                                        snackbar.setActionTextColor(Color.WHITE).show();
                                        activityWallpaperBinding.dialog.setVisibility(View.GONE);
                                    }
                                });
                                fos.close();
                                inputStream.close();
                            } catch (Exception e) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Snackbar.make(activityWallpaperBinding.recycler, "Download Fail", Snackbar.LENGTH_SHORT).show();
                                        activityWallpaperBinding.dialog.setVisibility(View.GONE);
                                    }
                                });
                                e.printStackTrace();
                            }
                            return false;
                        }
                    })
                    .preload();
        });
        activityWallpaperBinding.wallpaper.setOnClickListener(l -> {
            Glide.with(getApplicationContext())
                    .asBitmap()
                    .load(links.get(activityWallpaperBinding.recycler.getCurrentItem()))
                    .listener(new RequestListener<Bitmap>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                            Snackbar.make(activityWallpaperBinding.recycler, "Set Fail", Snackbar.LENGTH_SHORT).show();
                            activityWallpaperBinding.dialog.setVisibility(View.GONE);
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                            WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
                            try {
                                wallpaperManager.suggestDesiredDimensions(1080, 1920);
                                wallpaperManager.setBitmap(resource);
                                Snackbar.make(activityWallpaperBinding.recycler, "Set Success", Snackbar.LENGTH_SHORT).show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            activityWallpaperBinding.dialog.setVisibility(View.GONE);
                            return false;
                        }
                    })
                    .preload();
        });
        activityWallpaperBinding.down.setOnClickListener(l -> {
            List<Dao> historyBeans = daoUtils.queryAll();
            if (historyBeans != null && historyBeans.size() != 0) {
                Intent intent = new Intent(getApplicationContext(), HistoryActivity.class);
                intent.putExtra("title", "Download Record");
                startActivity(intent);
            } else {
                Snackbar.make(activityWallpaperBinding.recycler, "History does not exist", Snackbar.LENGTH_SHORT).show();
            }
            activityWallpaperBinding.dialog.setVisibility(View.GONE);
        });
    }

    @Override
    public void onBackPressed() {
        if (activityWallpaperBinding.dialog.getVisibility() == View.VISIBLE) {
            activityWallpaperBinding.dialog.setVisibility(View.GONE);
        } else {
            super.onBackPressed();
        }
        return;
    }

}